//
//  CountResoureVC.m
//  BCW
//
//  Created by Mac on 16/3/29.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "CountResoureVC.h"
#import "UIBarButtonItem+CustomItem.h"
#import "LotteryTableView.h"
#import "BCWNavItem.h"
#import "HBWNetDataManager.h"
#import "LotteryCellModel.h"
#import <SVProgressHUD.h>
#import "DateManager.h"
#import <UIImageView+WebCache.h>
#import "LotterySectionModel.h"

@interface CountResoureVC ()

@property (nonatomic,strong) NSTimer            *adTimer;

@property (nonatomic, strong) UIView            *headView;
@property (nonatomic, strong) UIView            *titleView;
@property (nonatomic, strong) LotteryTableView  *tableview;
@property (nonatomic, strong) UILabel           *noticL;

// 滚动时间
@property (nonatomic, assign) NSTimeInterval    timeInterval;
@property (nonatomic, strong) NSTimer           *timer;
@property (nonatomic, strong) UILabel           *lotteryStatuL;
@property (nonatomic, strong) UILabel           *prompt;

@property (nonatomic, strong) UIScrollView           *advert;

@end

@implementation CountResoureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    
    [SVProgressHUD showWithStatus:@"加载中..."];
    
    // 导航条
    [self setupNavBar];
    // 广告
    [self setupAdvertisingView];

    [self setupTableview];
    
    [self loadData];
    
    
    
    // 添加观察者 KVO
    [DateMgr addObserver:self forKeyPath:@"bcwDate" options:NSKeyValueObservingOptionNew context:nil];
    // 通知中心 添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"NeedReloadData" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endTime) name:@"endTime" object:nil];
    [self loadAdvertImg];
}

- (void)endTime{
    _lotteryStatuL.text = @"正在开奖";
}

- (void)loadAdvertImg{
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    param[@"type"] = @"2";
    [NetMgr advertImgWithParam:param Success:^(id responeseObj) {
        
        NSArray *arr =responeseObj[@"data"];
        [self setAdvertViewWithData:arr];
    } failuer:^(NSError *error) {
        
    }];
}


- (void)setAdvertViewWithData:(NSArray *)data{
    
    CGFloat x = 0;
    
    for (NSString *url in data) {
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(x, 0, _advert.width, _advert.height)];
        
        [img sd_setImageWithURL:[NSURL URLWithString:url]];
        [_advert addSubview:img];
        
        x += _advert.width;
    }
    
    if (data.count >= 2) {
        [self advertTimerWithCount:data.count];
    }
    
}

- (void)advertTimerWithCount:(NSInteger)count{
    _adTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(changeAdOffset:) userInfo:@(count) repeats:YES];
}

- (void)changeAdOffset:(NSTimer *)sender{
    //    NSLog(@"%li", [sender.userInfo integerValue]);
    if (_advert.contentOffset.x / _advert.width == [sender.userInfo integerValue] - 1) {
        [_advert setContentOffset:CGPointMake(0, 0) animated:YES];
        return;
        
    }
    //    else{
    [_advert setContentOffset:CGPointMake(_advert.contentOffset.x + _advert.width, 0) animated:YES];
    //    }
    
    
    //    _homeview.advertContainer.contentOffset = CGPointMake(_homeview.advertContainer.contentOffset.x + _homeview.advertContainer.width, 0);
    
    
}
- (void)refreshData{
    
    // 延迟30秒
    [self performSelector:@selector(loadData) withObject:nil afterDelay:31];
}

- (void)dealloc{
    
    [_adTimer invalidate];
    [self removeObserver:DateMgr forKeyPath:@"bcwDate"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)loadData{

    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    
    
    [NetMgr affichetextWithParam:nil Success:^(id responeseObj) {
        self.noticL.text = responeseObj[@"data"];
        [self beginTimer];
    } failuer:^(NSError *error) {
        
    }];
    
    // 投注参考
    [NetMgr countResoureWithParam:param Success:^(id responeseObj) {
        
        
//        NSArray *data = responeseObj[@"data"];
        
        if (![responeseObj isKindOfClass:[NSArray class]]) {
            [SVProgressHUD showErrorWithStatus:@"加载失败"];
            return;
        }
        
        NSMutableArray *bigModels = [[NSMutableArray alloc] init];
//        NSMutableArray *models = [[NSMutableArray alloc] init];
        
        for (int i = 0; i < [responeseObj count]; i ++) {
            NSDictionary *dic = responeseObj[i];
            
            LotterySectionModel *sectionModel = [[LotterySectionModel alloc] init];
            [sectionModel setTitleWithIssue:dic[@"issue"] result:dic[@"result"]];
            
            
            NSMutableArray *cellModels = [[NSMutableArray alloc] init];
            NSArray *arr = dic[@"data"];
            
            
            
            // 参考
            if (i == 0) {
                for (int j = 0; j < 5; j ++) {
                    LotteryCellModel *cellModel = [[LotteryCellModel alloc] initWithArr:arr[j]];
                    [cellModels addObject:cellModel];
                }
            }
            else{// 历史
                NSArray *tempArr = [dic[@"data"] componentsSeparatedByString:@"],"];
                
                for (int j = 0; j < tempArr.count; j++) {
                    NSString *tempStr = tempArr[j];
                    if (j == 0 || j == tempArr.count - 1) {
                        if (j == 0) {
                            tempStr = [tempStr substringFromIndex:2];
                        }
                        else{
                            tempStr = [tempStr substringWithRange:NSMakeRange(1, tempStr.length - 3)];
                        }
                        
                    }
                    else{
                        tempStr = [tempStr substringFromIndex:1];
                    }

                    
                    
                    LotteryCellModel *cellModel = [[LotteryCellModel alloc] initWithDataStr:tempStr];
                    [cellModels addObject:cellModel];
                }
                
            }
            
            sectionModel.cellModels = cellModels;
            
            [bigModels addObject:sectionModel];
            
            
//            NSArray *subData = data[i];
//            LotteryCellModel *model = [[LotteryCellModel alloc] initWithArr:subData];
//            [models addObject:model];
        }
        _tableview.cellModels = bigModels;
        _tableview.lotteryModel = _lotteryModel;
        [_tableview reloadData];
        [SVProgressHUD dismiss];
        // 添加投注参考
//        [bigModels addObject:models];
        
        // 历史
//        [NetMgr countResoureHistorySuccess:^(id responeseObj) {
//            
//            int i = 1;
//            int length = 29;
//            for (NSDictionary   *dic in responeseObj[@"data"]) {
////                LotteryCellModel *model = [[LotteryCellModel alloc] initWithDataStr:[]
////                NSLog(@"%@", [dic[@"prediction_num"] substringWithRange:NSMakeRange(i, length)]);
//                for (int j = 0; j < 5; j ++) {
//                    LotteryCellModel *model = [[LotteryCellModel alloc] initWithDataStr:[dic[@"prediction_num"] substringWithRange:NSMakeRange(i, length)]];
//                }
//                
//            }
//            
//            _tableview.cellModels = bigModels;
//            _tableview.lotteryModel = _lotteryModel;
//            [_tableview reloadData];
//            
//            [SVProgressHUD dismiss];
//        } failuer:^(NSError *error) {
//            
//        }];
        
        
    } failuer:^(NSError *error) {
        
    }];
    
}

- (void)reloadData{
    NSInteger phase = [[_lotteryModel.next_phase substringFromIndex:8] integerValue];
    _prompt.text = [NSString stringWithFormat:@"距离第%li期开奖剩余:", phase];

}

- (void)setupNavBar{
    self.navigationController.navigationBar.barTintColor = ThemeColor;
    
    // titleView
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];
    self.navigationItem.titleView = titleView;
//    self.titleView = titleView;
    
    UILabel *prompt = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleView.width, 20)];
    prompt.font = SystemFont(12);
    NSInteger phase = [[_lotteryModel.next_phase substringFromIndex:8] integerValue];
    prompt.text = [NSString stringWithFormat:@"距离第%li期开奖剩余:", phase];
    [titleView addSubview:prompt];
    prompt.textColor = WhiteColor;
    prompt.textAlignment = 1;
//    self.promptL = prompt;
    //    prompt.centerX = titleView.centerX;
    
    UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(0, prompt.bottom + 2, 80, 20)];
    status.backgroundColor = [UIColor whiteColor];
    
//    status.text = @"正在开奖";
    if (DateMgr.bcwDate.m == 0 && DateMgr.bcwDate.s == 0) {
        status.text = @"正在开奖";
    }
    else{
        status.text = [NSString stringWithFormat:@"%.2li:%.2li", DateMgr.bcwDate.m, DateMgr.bcwDate.s];
    }
    
    [titleView addSubview:status];
    status.textColor = ThemeColor;
    status.font = BoldFont(20);
    status.textAlignment = 1;
    status.centerX = prompt.centerX;
    _lotteryStatuL = status;
//    self.ststusL = status;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"return"
                                                 hightImage:@"return"
                                                     target:self
                                                     action:@selector(popVC)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"share-connection"
                                                  hightImage:@"share-connection"
                                                      target:self
                                                      action:@selector(rightClick)];
//    [self.navigationController setValue:[[BCWNavItem alloc] init] forKey:@"navigationItem"];
    
//    self.navigationItem = [[BCWNavItem alloc] init];
//    [self.navigationController.navigationBar popNavigationItemAnimated:NO];
//    [self.navigationController.navigationBar pushNavigationItem:[[BCWNavItem alloc] init] animated:NO];
    
}

- (void)rightClick{
    [SVProgressHUD showSuccessWithStatus:@"分享成功"];
}


- (void)setupAdvertisingView{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.width, 50)];
//    bgView.backgroundColor = PurpleColor;
    [self.view addSubview:bgView];
    self.headView = bgView;
    
    _advert = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, bgView.width, 35)];
//    advertising.image = [UIImage imageNamed:@"mai"];
    [bgView addSubview:_advert];
    
    // Notice
    UIView *noticeView = [[UIView alloc] initWithFrame:CGRectMake(0, _advert.bottom, _advert.width, 15)];
    noticeView.backgroundColor = WhiteColor;
    [bgView addSubview:noticeView];
    
    UIImageView *soundImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, noticeView.height)];
    soundImg.image = [UIImage imageNamed:@"radio"];
    soundImg.backgroundColor = WhiteColor;
    UILabel *noticText = [[UILabel alloc] initWithFrame:CGRectMake(soundImg.right + 5, 0, noticeView.width - soundImg.width, soundImg.height)];
    noticText.text = @"你一半，我一半，我们是好火伴。。。。";
    noticText.font = SystemFont(12);
    [noticText sizeToFit];
    self.noticL = noticText;
    
    [noticeView addSubview:noticText];
    [noticeView addSubview:soundImg];
    
//    [self beginTimer];
    
}

- (void)setupTableview{
    LotteryTableView *lotteryTable = [[LotteryTableView alloc] initWithFrame:CGRectMake(0, _headView.bottom, self.view.width, self.view.height - _headView.bottom) style:UITableViewStyleGrouped];
    _tableview = lotteryTable;
    [self.view addSubview:lotteryTable];
}

- (void)popVC{
    [self.navigationController dismissViewControllerAnimated:NO completion:nil];
}

- (void)beginTimer{
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(beginAnima) userInfo:nil repeats:NO];
}


- (void)beginAnima{
    
    CGFloat moveW = _noticL.width;
    if (_noticL.x == _headView.width) {
        moveW += _headView.width - 15;
    }
    // 时间
    NSTimeInterval interval = moveW / 35.f;// 30为速度
    _timeInterval = interval;
    
    [UIView animateKeyframesWithDuration:interval
                                   delay:0
                                 options:UIViewKeyframeAnimationOptionBeginFromCurrentState
                              animations:^{
                                  _noticL.x -= moveW;
    } completion:^(BOOL finished) {
        _noticL.x = _headView.width;
        
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(beginAnima) userInfo:nil repeats:NO];
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    _lotteryStatuL.text = [NSString stringWithFormat:@"%.2li:%.2li", DateMgr.bcwDate.m, DateMgr.bcwDate.s];
}

@end
